#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import json
import time
import base64
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
from Crypto.Random import get_random_bytes
import subprocess

class EncryptionManager:
    def __init__(self, secret_key: str = "qwertyuiop1234567654zaqwsxcderfv"):
        self.secret_key = secret_key.encode('utf-8')[:32].ljust(32, b'\0')
    
    def aes_encrypt(self, data: str) -> str:
        """AES256加密"""
        iv = get_random_bytes(16)
        cipher = AES.new(self.secret_key, AES.MODE_CBC, iv)
        padded_data = pad(data.encode('utf-8'), AES.block_size)
        encrypted = cipher.encrypt(padded_data)
        return base64.b64encode(iv + encrypted).decode('utf-8')

def create_encrypted_payload(data: dict) -> dict:
    """创建加密载荷"""
    # 添加时间戳
    data['timestamp'] = int(time.time())
    
    # 转换为JSON字符串
    json_string = json.dumps(data, ensure_ascii=False)
    
    # 加密
    encryption_manager = EncryptionManager()
    encrypted_data = encryption_manager.aes_encrypt(json_string)
    
    return {"encrypted_data": encrypted_data}

def publish_activity_with_curl(encrypted_payload: dict, activity_title: str):
    """使用curl发送加密的活动发布请求"""
    
    # 构建curl命令
    curl_data = json.dumps(encrypted_payload, ensure_ascii=False)
    
    curl_command = [
        'curl', '-X', 'POST', 
        'http://124.71.77.44:2233/activities/',
        '-H', 'Content-Type: application/json; charset=utf-8',
        '-H', 'Content-Encrypted: true',
        '-H', 'Encryption-Algorithm: AES256',
        '-d', curl_data
    ]
    
    print(f"🚀 发布活动: {activity_title}")
    print(f"📝 curl命令:")
    print(' '.join([f'"{arg}"' if ' ' in arg else arg for arg in curl_command]))
    print()
    
    try:
        # 执行curl命令
        result = subprocess.run(curl_command, 
                              capture_output=True, 
                              text=True, 
                              timeout=30)
        
        print(f"📨 响应状态码: {result.returncode}")
        print(f"📄 响应内容: {result.stdout}")
        if result.stderr:
            print(f"❌ 错误信息: {result.stderr}")
        print("-" * 60)
        return result.returncode == 0
        
    except subprocess.TimeoutExpired:
        print("❌ 请求超时")
        return False
    except Exception as e:
        print(f"❌ 执行curl失败: {e}")
        return False

def main():
    """主函数 - 发布两个测试活动"""
    
    print("🎯 开始发布测试活动到北京坐标...")
    print()
    
    # 艺术作品图片数据（从art-works-data.md选择）
    art_images = [
        "https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/art_works/share_154f5afcc73ab7814a745378c6dd2846_edit_391954352758421.png",
        "https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/art_works/share_06409c288f6c65c4f600bddf9283602f_edit_391871265051142.png",
        "https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/art_works/share_0e5b4a2b28ed3de4b0bd82dbf7c6903d_edit_391867197811038.png",
        "https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/art_works/share_0f12f2ab2759993eafd5c0dd836ad67d_edit_391959430881857.png",
        "https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/art_works/share_c2cfd9ded965c38680f00a21a01386f4_edit_391916608718322.png",
        "https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/art_works/share_cdec2b9dcd00187206c05ebebd34b362_edit_391829318571981.png"
    ]
    
    # 测试活动1: 聚餐活动
    activity1_data = {
        "activityTitle": "🍽️ 北京朝阳区聚餐活动",
        "publisherId": 62,
        "publisherNickname": "Flutter测试用户",
        "activityPublishTime": "2025-01-30 18:00:00",
        "longitude": 116.404,
        "latitude": 39.915,
        "activityDetails": "周末聚餐，一起品尝北京美食！地点在朝阳区，欢迎大家参加。",
        "activityLocation": "北京市朝阳区CBD商务区",
        "activityImages": art_images[0:3],  # 使用前3张图片
        "activityType": ["AA"],
        "activityTags": ["聚餐", "周末", "美食"],
        "activityMaxParticipants": 8,
        "publisherAvatarUrl": "http://app.playtruly.cn/system/avatar.jpg",
        "publisherSignature": "喜欢美食，喜欢交朋友",
        "publisherTags": ["美食爱好者", "测试用户"],
        "free": 1
    }
    
    # 测试活动2: 户外运动
    activity2_data = {
        "activityTitle": "🏃‍♂️ 北京朝阳公园晨跑",
        "publisherId": 62,
        "publisherNickname": "Flutter测试用户",
        "activityPublishTime": "2025-01-31 07:00:00", 
        "longitude": 116.404,
        "latitude": 39.915,
        "activityDetails": "早晨一起在朝阳公园晨跑，锻炼身体，享受新鲜空气！",
        "activityLocation": "北京市朝阳区朝阳公园",
        "activityImages": art_images[3:6],  # 使用后3张图片
        "activityType": ["我买单"],
        "activityTags": ["运动", "晨跑", "健康"],
        "activityMaxParticipants": 15,
        "publisherAvatarUrl": "http://app.playtruly.cn/system/avatar.jpg", 
        "publisherSignature": "热爱运动，享受生活",
        "publisherTags": ["运动达人", "测试用户"],
        "free": 1
    }
    
    activities = [activity1_data, activity2_data]
    success_count = 0
    
    # 发布所有活动
    for i, activity_data in enumerate(activities, 1):
        print(f"📋 准备发布第 {i} 个活动...")
        print(f"🎯 标题: {activity_data['activityTitle']}")
        print(f"📅 时间: {activity_data['activityPublishTime']}")
        print(f"📍 位置: {activity_data['activityLocation']}")
        print(f"👥 最大人数: {activity_data['activityMaxParticipants']}")
        print(f"🏷️ 标签: {activity_data['activityTags']}")
        print(f"🖼️ 图片数量: {len(activity_data['activityImages'])}")
        print()
        
        # 创建加密载荷
        encrypted_payload = create_encrypted_payload(activity_data.copy())
        print(f"🔒 加密数据长度: {len(encrypted_payload['encrypted_data'])}")
        
        # 发送请求
        if publish_activity_with_curl(encrypted_payload, activity_data['activityTitle']):
            success_count += 1
            print(f"✅ 第 {i} 个活动发布成功!")
        else:
            print(f"❌ 第 {i} 个活动发布失败!")
        
        print()
        
        # 等待1秒避免请求过快
        time.sleep(1)
    
    print(f"🎉 活动发布完成！成功: {success_count}/{len(activities)}")
    print()
    print("📱 现在可以重新运行Flutter应用，首页应该能显示这些活动了！")

if __name__ == "__main__":
    main()
